import axios, { AxiosRequestConfig, Method } from 'axios'
import { showToast, showLoadingToast, closeToast, showNotify } from 'vant';

import router from '../router/index'

//创建toast 


const service = axios.create({
  baseURL: '/api',
  timeout: 5000 * 5
})
service.defaults.headers.post['Content-Type'] = 'application/json'



// Request interceptors
service.interceptors.request.use(
  config => {
    //First 每次请求Api 则开始Loading加载
    /*  showLoadingToast({
       type: 'loading',
       message: '加载中',
       forbidClick: true,
     }); */

    //Second 每次请求 如果Token不为空 则加在请求头部 作为token令牌使用
    if (localStorage.getItem('token') != null) {
      config.headers['authorization'] = localStorage.getItem('token')
    }

    //Thired
    return config
  },
  error => {
    return Promise.reject(error)
  }
)


service.interceptors.response.use(response => {

  /**
   * 1. 清除Toast弹窗
   * 2. 判断是否放行
   *  a. 成功返回data数据
   *  b. 提示错误信息else if(){} 
   */
  // closeToast()
  if (response.data.code == 2000) {
    return response;
  } else {
    //如果后台message为空则自定义错误
    showToast({
      message: response.data.message || "网络出错",
      position: 'top',
    })
    return response
  }
}, (error) => {
  //清除加载框
  // closeToast()
  if (error.response.status == 401) {
    console.log(error.response.statusText);
    showNotify({
      message: "Unauthorized Token过期 系统自动为你删除了token 请重新登录",
      type: 'warning'
    })
    localStorage.removeItem("token")
    router.push("/login")
  }
  //判断是否放行放行拦截Res
  return Promise.reject(error)
})


//自定义Get Api请求格式
export const createAPI = (url: string, method: Method = 'get', params: any = undefined, data: any = undefined) => {
  let config: AxiosRequestConfig = {}
  config.url = url
  config.method = method
  if (params !== undefined) {
    config.params = params
  }
  //发送post请求封装data
  if (method != 'get' && data !== undefined) {
    config.data = data
  }

  return service(config)
}

export const createFormAPI = (url: string, method: Method, data: any) => {
  let config: AxiosRequestConfig = {}
  config.url = url
  config.method = method
  config.data = data
  config.headers = {
    'Cache-Control': 'no-cache',
    'Content-Type': 'application/x-www-form-urlencoded'
  }
  config.responseType = 'json'
  config.transformRequest = [
    function (data) {
      let ret = ''
      for (let it in data) {
        ret += encodeURIComponent(it) + '=' + encodeURIComponent(data[it]) + '&'
      }
      return ret
    }
  ]
  return service(config)
}

